package com.dm0858.bianmin.mine.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.mine.bean.CarBeanData;
import com.dm0858.bianmin.mine.bean.HouseBeanData;
import com.dm0858.bianmin.mine.bean.NormalBeanData;
import com.dm0858.bianmin.ui.activity.CacheUtils;
import com.dm0858.bianmin.ui.activity.ReleaseBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.util.ConvertUtils;


public class ReleaseAdapter  extends ArrayAdapter {
    private final int resourceId;
    private String [] releaseItems;

    private Context contexts;
    private List<String> photoLists = new ArrayList<String>();
    private int i = 0;
    private Activity activity;
    private HashMap<Integer, View> mHashMap = new HashMap<Integer, View>();

    private int typeInt = 0;
    private NormalBeanData normal;
    private HouseBeanData house;
    private CarBeanData car;

    public ReleaseAdapter(Context context, int textViewResourceId, String [] objects,Activity ac) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
        contexts = context;
        releaseItems = objects;
        activity = ac;

    }

    public ReleaseAdapter(Context context, int textViewResourceId, String [] objects, Activity ac, NormalBeanData normal,int typeInt) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
        contexts = context;
        releaseItems = objects;
        activity = ac;
        this.normal = normal;
        this.typeInt = typeInt;
    }

    public ReleaseAdapter(Context context, int textViewResourceId, String [] objects, Activity ac, HouseBeanData house,int typeInt) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
        contexts = context;
        releaseItems = objects;
        activity = ac;
        this.house = house;
        this.typeInt = typeInt;
    }

    public ReleaseAdapter(Context context, int textViewResourceId, String [] objects, Activity ac, CarBeanData car,int typeInt) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
        contexts = context;
        releaseItems = objects;
        activity = ac;
        this.car = car;
        this.typeInt = typeInt;
    }




    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        MyViewHolder holder = null;

        final String title = (String) getItem(position); // 获取当前项的popupBean实例
        if(mHashMap.get(position) == null){
            convertView = LayoutInflater.from(contexts).inflate(resourceId, null);//实例化一个对象


            holder = new MyViewHolder();



            if (title.equals("内容")|| title.equals("车辆描述")|| title.equals("房源描述")) {

                holder.typeTwo = convertView.findViewById(R.id.typeTwo);
                holder.typeTwo.setVisibility(View.VISIBLE);

                holder.OKBtn = convertView.findViewById(R.id.OKBtn);
                holder.editText = convertView.findViewById(R.id.editText);
                if (typeInt == 0){
                    holder.editText.setText(normal.getExplain() + "");
                } else if (typeInt == 10) {
                    holder.editText.setText(house.getExplain()+ "");
                } else if (typeInt == 17)
                    holder.editText.setText(car.getExplain()+ "");

                save(title, holder.editText.getText().toString());
                holder.editText.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        // 输入的内容变化的监听
                        save(title,s.toString());
                    }


                    @Override
                    public void afterTextChanged(Editable s) {



                    }
                });

                holder.OKBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        releaseOk();
                    }
                });
            }else if (title.equals("地址") ||title.equals("看车地址") ||title.equals("地区")){

                holder.typeThree = convertView.findViewById(R.id.typeThree);
                holder.typeThree.setVisibility(View.VISIBLE);

                final Button addressText = convertView.findViewById(R.id.addressText);
                addressText.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            city(addressText,title);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });


            }else {
                holder.typeOne = convertView.findViewById(R.id.typeOne);
                holder.typeOne.setVisibility(View.VISIBLE);
                holder.orderEditText = convertView.findViewById(R.id.orderEditText);
                holder.orderEditText.setText(getText(position) + "");
                save(title, holder.orderEditText.getText().toString());
                holder.orderEditText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                        save(title,s.toString());
                    }


                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
            }




            holder.titleView = convertView.findViewById(R.id.titleView);




            mHashMap.put(position, convertView);

            convertView.setTag(holder);
            if (title.equals("内容")|| title.equals("车辆描述")|| title.equals("房源描述")) {
                setListViewHeight(500,holder.typeTwo);

                //holder.typeThree.setVisibility(View.GONE);
                // holder.typeOne.setVisibility(View.GONE);

            }
        }else {
            convertView = mHashMap.get(position);
            holder = (MyViewHolder) convertView.getTag();
        }



        holder.titleView.setText(title);






        return convertView;
    }



    private String getText(int position) {
        if (typeInt == 0){
            switch (position) {
                case 0:
                    return normal.getTitle();
                case 1:
                    return "";
                case 2:
                    return normal.getBeian();
                case 4:
                    return normal.getAddr();
                case 5:
                    return normal.getUsername();
                case 6:
                    return normal.getTel();
            }
        }
        else if (typeInt == 10) {
            switch (position){
                case 0:
                    return house.getTitle();
                case 2:
                    return house.getAddr();
                case 3:
                    return house.getXiaoqu();
                case 4:
                    return house.getHuxing();
                case 5:
                    return house.getMianji();
                case 6:
                    return house.getJiage();
                case 7:
                    return house.getUsername();
                case 8:
                    return house.getTel();
            }
        }
        else if (typeInt == 17) {
            switch (position){
                case 0:
                    return car.getTitle();
                case 1:
                    return car.getChengxing();
                case 2:
                    return car.getLicheng();
                case 3:
                    return car.getShangpai();
                case 4:
                    return car.getPailiang();
                case 5:
                    return car.getJiage();
                case 7:
                    return car.getAddr();
                case 8:
                    return  car.getUsername();
                case 9:
                    return car.getTel();
            }
        }
        return "";
    }


    public void releaseOk() {

        onToggleClickListener.onDoClick();








        //Log.d("","可以开始上传工作了");
        //到这了说明可以开始上传数据了



    }








    private void save(String title, String text) {
        List<ReleaseBean> releaseBeans = getReleaseBean();
        Gson g = new Gson();
        if (releaseBeans.size() == 0 ){
            //直接添加
            ReleaseBean releaseBean = new ReleaseBean();
            releaseBean.setTitle(title);
            releaseBean.setContent(text);
            releaseBeans.add(releaseBean);
            String jsonString = g.toJson(releaseBeans);

            CacheUtils.setReleaseContent(contexts,jsonString);

        }else {
            //判断有没有这个数据
            boolean isSave = false;
            for (int i = 0;i < releaseBeans.size();i++) {
                ReleaseBean releaseBean = releaseBeans.get(i);
                if (releaseBean.getTitle().equals(title)) {
                    //先删除
                    releaseBeans.remove(releaseBean);
                    //说明有保存过，需要再次更换
                    ///但是要先判断，是不是空的字符串
                    if (releaseBean.getContent().equals("")) {
                        //如果是空，，直接保存删除过的数据，不添加。为了后面进行判断是否全部填写完成
                        String jsonString = g.toJson(releaseBeans);
                        CacheUtils.setReleaseContent(contexts,jsonString);
                    }else {
                        releaseBean.setContent(text);
                        isSave = true;
                        //再保存
                        releaseBeans.add(releaseBean);
                        String jsonString = g.toJson(releaseBeans);
                        CacheUtils.setReleaseContent(contexts,jsonString);
                    }


                }
            }
            if (isSave == false) {
                //没保存过
                ReleaseBean releaseBean = new ReleaseBean();
                releaseBean.setTitle(title);
                releaseBean.setContent(text);
                releaseBeans.add(releaseBean);
                String jsonString = g.toJson(releaseBeans);
                CacheUtils.setReleaseContent(contexts,jsonString);


            }
        }
    }



    private void city(final Button addressText, final String title) throws IOException {
        ArrayList<Province> data = new ArrayList<>();
        String json = ConvertUtils.toString(getContext().getAssets().open("city.json"));
        data.addAll(JSON.parseArray(json, Province.class));
        AddressPicker picker = new AddressPicker((Activity) getContext(), data);
        picker.setShadowVisible(true);
        picker.setTextSizeAutoFit(false);

        picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                String address = province.getAreaName() + " " + city.getAreaName() + " " + county.getAreaName() + " ";
                addressText.setText(address);

                save(title,address);
            }
        });

        picker.show();
    }


    //为listview动态设置高度（有多少条目就显示多少条目）
    public void setListViewHeight(int totalHeight, RelativeLayout view) {
        // 获取gridview的adapter
        if (this == null) {
            return;
        }

        // 获取gridview的布局参数
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = totalHeight;
        view.setLayoutParams(params);
    }






    public static class MyViewHolder {
        RelativeLayout typeOne;
        RelativeLayout typeTwo;
        RelativeLayout typeThree;
        EditText editText;
        EditText orderEditText;
        Button OKBtn;
        TextView titleView;
    }



    //定义借口
    // 第一步，定义接口，接口里面有个 设置点击的监听
    public interface OnToggleClickListener{
        void onDoClick();
    }


    // 第二步，在当前类中定义一个接口的变量，以便接受其他类实现接口后传过来的接口
    private OnToggleClickListener onToggleClickListener;


    // 第三步，当当前类中写一个 public的设置接口的方法，参数是我们写的接口
    // 这样其他类一旦调用了setToggleClickListener，就必须实现我们写的接口
    public void setToggleClickListener(OnToggleClickListener onToggleClickListener){
        if(onToggleClickListener != null){
            this.onToggleClickListener = onToggleClickListener;
        }
    }




    /***
     *  把StringJson转换为list类型
     */
    public <ReleaseBean> List<com.dm0858.bianmin.ui.activity.ReleaseBean> getReleaseBean() {
        List<com.dm0858.bianmin.ui.activity.ReleaseBean> datalist=new ArrayList<com.dm0858.bianmin.ui.activity.ReleaseBean>();
        String strJson = CacheUtils.getReleaseContent(contexts);
        if (null == strJson || strJson.equals("")) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(strJson, new TypeToken<List<com.dm0858.bianmin.ui.activity.ReleaseBean>>() {
        }.getType());
        return datalist;

    }

}